package com.geek.enhnce.plugin.manager;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.alibaba.fastjson.JSON;

@SuppressWarnings("serial")
public class SpringPluginManagerControl extends HttpServlet {
	private WebApplicationContext context;
	private SpringPluginFactory pluginFactory;

	@Override
	public void init() throws ServletException {
		super.init();
		context = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
		pluginFactory = context.getBean(SpringPluginFactory.class);
	}

	//读取远程仓库配置文件
	public void openRemoteSite(String siteUrl){
		try {
			PluginSite site = getSite(siteUrl);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public PluginSite getSite(String urlValue) throws Exception {
		URL url = new URL(urlValue);
		InputStream input = url.openStream();
		ByteArrayOutputStream output = new ByteArrayOutputStream();
		copy(input, output);
		String jsonValue = output.toString("UTF-8");
		return JSON.parseObject(jsonValue, PluginSite.class);
	}

	/**
	 * 文件读取
	 * @param source
	 * @param out
	 * @return
	 * @throws IOException
	 */
	private long copy(InputStream source, ByteArrayOutputStream out) throws IOException {
		long nread = 0L;
		byte[] buf = new byte[8192];
		int len ;
		while((len = source.read(buf)) > 0){
			out.write(buf, 0, len);
			nread += len;
		}
		return nread;
	}
}
